//
//  WSGWebViewController.m
//  oneDollar
//
//  Created by Laki on 16/6/16.
//  Copyright © 2016年 com.Laki.corder. All rights reserved.
//

#import "WSGWebViewController.h"
#import <WebKit/WebKit.h>

@interface WSGWebViewController ()<WKNavigationDelegate>
/** 进度条*/
@property (weak, nonatomic) IBOutlet UIProgressView *progress;
/** WKWebView*/
@property (nonatomic,strong) WKWebView *web;
@end

@implementation WSGWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    /*
    NSString *js = @"window.webkit.messageHandlers.observe.postMessage(document.body.innerText);";
    
    WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
    [config.userContentController addUserScript:script];
    
    [config.userContentController addScriptMessageHandler:self name:@"observe"];
    */
    
//    var styleTag = document.createElement("style");

    
    // 创建webView的Frame 64为导航控制器的高度
    CGRect webFrame = CGRectMake(0, 0, ScreenW, ScreenH - 64);
    
    // 创建一个可跳转的网页
    WKWebView *web = [[WKWebView alloc] initWithFrame:webFrame];
    
    // 保存属性
    self.web = web;
    web.navigationDelegate = self;
    // 插入进度条
    [self.view insertSubview:web atIndex:0];
    
    // 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    
    // 网页加载请求对象
    [web loadRequest:request];
    
    // 监听WebView进度条新值属性改变
    [web addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    // 监听WebView标题新值属性改变
    [web addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];

}

/*
 * 代理方法获取整个网页的数据
 */
/*
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSString *str = (NSString *)message.body;
}*/

#pragma mark --------------------
#pragma mark 当新值发生改变则调用该方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    // 判断是否是监听到标题的改变
    if ([keyPath isEqualToString:@"title"]) {
        self.navigationItem.title = self.web.title;
    }
    
    // 判断是否是监听到进度条的改变
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progress.progress = self.web.estimatedProgress;
        self.progress.hidden = self.web.estimatedProgress >= 1;
    }
}

#pragma mark --------------------
#pragma mark 移除观察者
- (void)dealloc{
    // KVO一定要移除观察者
    [self.web removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.web removeObserver:self forKeyPath:@"title"];
}
@end
